package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.config.properties.AliOSSUtil;
import com.jsb.laundry.dao.RiderUserInfoDao;
import com.jsb.laundry.jobs.WechatAccessToken;
import com.jsb.laundry.utils.RedisUtil;
import io.swagger.annotations.Api;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.Base64;

@Api(tags = {"我的内推，我的客户二维码生成"})
@RestController
@RequestMapping("/sun")
public class SunController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SunController.class);


    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private RiderUserInfoDao userInfoDao;

    /**
     * 生成太阳码（appUserId、userType、page、env_version）
     *
     * @param data
     * @return
     * @throws Exception
     */
    @PostMapping("/getSunImg")
    public WebResponse addOrderListDetails(@RequestBody String data) throws Exception {
        JSONObject jsonObject1 = JSON.parseObject(data);
        String appUserId = jsonObject1.getString("appUserId"); //邀请人id
        String userType = jsonObject1.getString("userType"); //邀请人类型 用户1 ，骑手2
        String page = jsonObject1.getString("page"); //去用户小程序端首页(pages/clothes/index) 去骑手端首页(pages/mytask/index)
        String envVersion = jsonObject1.getString("env_version"); //0:去用户小程序端首页(pages/clothes/index) 1: 去骑手端首页(pages/mytask/index)

        if (JSBUtil.isEmptyString(page) || JSBUtil.isEmptyString(userType) || JSBUtil.isEmptyString(appUserId) || JSBUtil.isEmptyString(envVersion)) {
            return WebResponse.failOfParameter();
        }

        //根据appUserId查询对应的主键id （登录后配合userType（t） 反向查询出id）
        String id = "";
        String accessToken = "";

        if ("2".equals(userType)) { // 骑手2
            id = userInfoDao.getRiderInfo(appUserId);
        }

        if ("pages/user/index".equals(page)) {
            accessToken = WechatAccessToken.getWxAccessToken("wx66259c2db83de8c2","a751a2d916092083cbd85d4f58ffc0b5");//骑手
        } else {
            accessToken = WechatAccessToken.getWxAccessToken("wxb730137b1ae9f679","86fcb97161a0ea96bc082f3b58d0e8ed");//用户
        }

        /**
         * 获取access_token
         */
        //根据公众号的openid查询unionid
        String url = String.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", accessToken);


        CloseableHttpClient client11 = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);

        JSONObject jsonb = new JSONObject();
        jsonb.put("scene", String.format("a=%s&t=%s", id, userType)); // a:邀请人主键id , t: 用户0 ，骑手1
        jsonb.put("page", page); //跳转页面
        jsonb.put("env_version", envVersion); //跳转对应版本


//         设置请求头和请求体
        StringEntity postingString = new StringEntity(jsonb.toString(), "UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");

        // 发送请求并获取响应
        HttpResponse response = client11.execute(post);

        HttpEntity entity = response.getEntity();
        byte[] byteArray = EntityUtils.toByteArray(entity);
        if (byteArray.length < 2000) {
            return WebResponse.success("200001","太阳码生成异常");
        }
//         将字节数组转为Base64字符串，使用URL和文件名安全字符集

        String base64String = Base64.getEncoder().encodeToString(byteArray);

        // 返回带有Base64编码的图片数据给前端
        String imageDataUri = "data:image/jpeg;base64," + base64String;

        // 若成功将bytes转成base64并返回给前端
        MultipartFile multipartFile = base64ToMultipartFile(base64String);
        String path = AliOSSUtil.uploadFile(multipartFile, "userInfo");


        return WebResponse.successData(path);
    }

    /**
     * base64Data转 MultipartFile上传阿里云
     *
     * @param base64String
     * @return
     * @throws IOException
     */
    public static MultipartFile base64ToMultipartFile(String base64String) throws IOException {
        byte[] content = org.apache.commons.codec.binary.Base64.decodeBase64(base64String);
        MockMultipartFile mockMultipartFile = new MockMultipartFile(
                "file", "wechatRiderSunImgCodeBase64Str.png", ContentType.APPLICATION_OCTET_STREAM.toString(), content);
        return mockMultipartFile;
    }

    /**
     * url内容编码
     *
     * @param str 内容
     * @return 编码后的内容
     */
    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    private static BufferedImage bytesToBufferedImage(byte[] bytes) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

        BufferedImage image = null;
        try {
            image = ImageIO.read(bis);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bis.close();
        }

        return image;
    }


    /**
     * bufferedImage转base64
     *
     * @param bufferedImage
     * @return
     */
    public static String getBase64String(BufferedImage bufferedImage) {
        String formatName = ImageIO.getImageWritersByMIMEType("image/jpeg").next().getOriginatingProvider().getFileSuffixes()[0]; // 获取 BufferedImage 对应的格式
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, formatName, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();
        String base64 = Base64.getEncoder().encodeToString(bytes);
        return base64;
    }


    /**
     * 文件流转MultipartFile
     *
     * @param image
     * @return
     * @throws IOException
     */
    public static MultipartFile convertToMultipartFile(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String formatName = ImageIO.getImageWritersByMIMEType("image/jpeg").next().getOriginatingProvider().getFileSuffixes()[0]; // 获取 BufferedImage 对应的格式
        ImageIO.write(image, formatName, baos);
        byte[] bytes = baos.toByteArray();
        return new MultipartFile() {
            @Override
            public String getName() {
                return "image.jpg";
            }

            @Override
            public String getOriginalFilename() {
                return "image.jpg";
            }

            @Override
            public String getContentType() {
                return "image/jpeg";
            }

            @Override
            public boolean isEmpty() {
                return bytes.length == 0;
            }

            @Override
            public long getSize() {
                return bytes.length;
            }

            @Override
            public byte[] getBytes() throws IOException {
                return bytes;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(bytes);
            }

            @Override
            public void transferTo(File file) throws IOException, IllegalStateException {
                new FileOutputStream(file).write(bytes);
            }
        };
    }


    /**
     * MultipartFile直接转base64
     *
     * @param multiPartFile
     * @return
     */
    public static String getBase64String(MultipartFile multiPartFile) {
        String baseStr = null;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            baseStr = encoder.encode(multiPartFile.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        baseStr = baseStr.replaceAll("\r\n", "");
        return baseStr;
    }
}
